<template>
  <div class="confirm-order">
    <Header />
    <div class="nav-outer">
      <div class="nav-1200 area1190">
        <span>首页</span> > <span>商城首页</span> > <span>订单结算</span> >
        <div class="nav-right">
          <span>售后政策</span>
          <i class="center-line"></i>
          <span>咨询客服</span>
        </div>
      </div>
    </div>
    <!-- 内容层 -->
    <div class="middle-box">
      <div class="content-box">
        <h3>确认订单信息</h3>
        <div class="table-box">
          <div class="table-title flex ai-c">
            <div class="flex-1">车型信息</div>
            <div class="col-2">意向金</div>
            <div class="col-3">数量</div>
            <div class="col-4">小计</div>
          </div>
          <div class="table-list flex ai-c">
            <div class="flex-1">
              <div class="flex">
                <img :src="product.pic" class="table-img" />
                <div class="title-box flex flex-d jc-c">
                  <p class="title">{{ product.name }}</p>
                  <span>{{ product.subTitle }}</span>
                </div>
              </div>
            </div>
            <div class="col-2 mobile-money">
              <span class="mobile-yxj">意向金：</span>
              ¥{{ product.price }}
            </div>
            <div class="col-3 flex jc-c mobile-s-num">
              <el-button-group class="flex">
                <el-button
                  size="mini"
                  icon="el-icon-minus"
                  @click="changeNum('-')"
                ></el-button>
                <el-input v-model="num" class="num"  size="mini" :min="1"  :max="10"></el-input>
                <el-button
                  size="mini"

                  icon="el-icon-plus"
                  @click="changeNum('+')"
                ></el-button>
              </el-button-group>
            </div>
            <div class="col-4 mobile-totle">￥{{ total }}</div>
          </div>
        </div>
        <div class="info-box flex ai-c">
          <span><span style="color: red">*</span>选择支付方式:</span>
          <!--<el-input placeholder="请输入您的姓名" v-model="input1"></el-input>-->
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>

        <div class="info-box flex ai-c" style="border:none!important">
          <span><span style="color: red;">*</span>选择收获地址:</span>
          <!--<el-input placeholder="请输入您的姓名" v-model="input1"></el-input>-->
<!--          <el-select v-model="addressValue" placeholder="请选择" filterable>-->
<!--            <el-option-->
<!--                v-for="item in address"-->
<!--                :key="item.id"-->
<!--                :label="item.name+'-&#45;&#45;&#45;&#45;'+item.province+item.city+item.region+item.detailAddress"-->
<!--                :value="item.id"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
        </div>
      <Address :list="address" @pushIdToOrder="addressIdEvent"></Address>
        <div class="info-box flex ai-c">
          <span><span style="color: red">*</span>选择物流方式:</span>
          <!--<el-input placeholder="请输入您的姓名" v-model="input1"></el-input>-->
          <el-select v-model="deliveryCompany" placeholder="请选择">
            <el-option
                v-for="item in deliveryCompanys"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </div>

        <!--<div class="info-box flex ai-c">-->
        <!--<span>*您的电话:</span>-->
        <!--<el-input placeholder="请输入您的电话" v-model="input2"></el-input>-->
        <!--</div>-->
        <div class="footer-box flex jc-fe ai-c">
          <span
            >商品合计: <b>￥{{ total }} </b></span
          >
          <el-button type="danger" class="sub-btn" @click="goOrder(id, total)"
            >提交订单</el-button
          >
        </div>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import Address from "@/components/Address";
import wx from "weixin-js-sdk";

import axios from "axios";
import empty from "@/utils/common";
export default {
  name: "confirmOrder",
  components: {
    Header,
    Footer,
    Address,
  },
  data() {
    return {
      num: 0,
      input1: "",
      input2: "",
      product: {},
      totalPrice: "0.00",
      order: {},
      options: [
        {
          label: "支付宝",
          value: "1",
        },
        {
          label: "微信",
          value: "2",
        },
        {
          label: "余额",
          value: "3",
        },
        {
          label: "授信额度支付",
          value: "4",
        },
      ],
      value: "1",
      addressValue:'',
      address:[],
      postAddres:'',
      deliveryCompany:'物流',
      deliveryCompanys: [
        {
          label: "物流",
          value: "物流",
        },
        {
          label: "自提",
          value: "自提",
        },
        {
          label: " 快递",
          value: "快递",
        }
      ],
    };
  },
  created() {
    this.product = this.$route.query;
    this.num = this.product.buyNum;
    this.totalPrice = this.num * this.product.price;
    this.getAddress();
  },
  methods: {
    changeNum(type) {
      if (type == "+") {
        this.num++;
      } else {
        if (this.num <=1) return false;
        if (this.num !== 1) this.num--;
      }
    },
    goOrder(id, total) {
      var _this = this;
      if(empty(this.postAddres)){
        console.log(this);
        _this.$message({
          showClose: true,
          message: '请选择收获地址',
          type: "warning",
        });
        return false;
      }
      console.log("product:"+_this.product);
      let postData = {
        cartPromotionItemList: [
          {
            growth: 0,
            integration: 0,
            price: (total/this.num).toFixed(2),
            productAttr: '[{"key":"版本型号","value":"预置属性值"}]',
            productBrand: "晶马",
            productCategoryId: _this.product.productCategoryId,
            productId: _this.product.id,
            productName: _this.product.name,
            productPic: _this.product.pic,
            productSkuCode: _this.product.skuStockList[0].skuCode,
            productSkuId: _this.product.skuStockList[0].id,
            productSn: _this.product.productSn,
            productSubTitle: _this.product.subTitle,
            promotionType: "2",
            quantity: _this.num,
            memberReceiveAddressId:_this.postAddres,
            deliveryCompany:_this.deliveryCompany
          },
        ],
        quantity:this.num,
        orderType:0,
        deliveryCompany:this.deliveryCompany,
        memberReceiveAddressId: this.postAddres,
        payType: this.value,
        sourceType: 3,
        // "useIntegration": 0
      };

      _this.$http
        .post("/order/buynowgenerateOrder", postData)
        .then(function (response) {
          _this.order = response.data.order;
          _this.$message({
            showClose: true,
            message: response.message,
            type: "success",
          });
          //调用支付接口生成二维码
          if (_this.value == 1) {
            let aliData = {
              body: "内容",
              out_trade_no: _this.order.orderSn,
              return_url: "https://www.baidu.com",
              subject: "wenju",
              total_amount: _this.order.payAmount,
            };
            _this.aliPay(aliData);
          }
          if (_this.value == 2) {
            let wechatData = {
              body: "订单-晶马整车商城",
              notifyurl: "www.baidu.com",
              outTradeNo: _this.order.orderSn,
              totalFee: _this.order.payAmount,
              productId: _this.product.id,
              tradeType: "NATIVE",
            };
              _this.wechatPay(wechatData);

          }
          if (_this.value == 3) {
            let wechatData = {
              orderNo: _this.order.orderSn,
            };
            _this.remain(wechatData);
          }
          if (_this.value == 4) {
            let wechatData = {
              orderNo: _this.order.orderSn,
            };
            _this.creditpay(wechatData);
          }
          //_this.$router.push({path:'/payment',query: _this.order})
        });
    },
    wechatPay(postData) {
      var _this = this;
      //判断是否是手机端
      if(_this._isMobile()){
        //获取手机端
        postData.tradeType = 'MWEB';
        postData.openId = window.localStorage.getItem('openid');
        _this.$http
            .post("/we-chat/wxpay", postData)
            .then(function (response) {
              if(!empty(response.data)){
                _this.wexinPay(response.data,_this.tosuccess);
              }

            });
        return false;
      }


      _this.$http
        .post("/order/wchatcode/query", postData)
        .then(function (response) {
          _this.order.code_url = response.data.code_url;
          _this.order.payType = _this.value;
          _this.$message({
            showClose: true,
            message: response.message,
            type: "success",
          });
            //调用支付接口生成二维码
            _this.$router.push({ path: "/payment", query: _this.order });

        });
    },
    aliPay(postData) {
      // var _this = this;
      // _this.$http.post('/pay/aliPay',postData).then(function (response) {
      //     window.console.log(response)
      //     window.debugger;
      //     _this.order.payType = _this.value;
      //
      //     document.querySelector('body').innerHTML = response;
      //
      //     const div = document.createElement('div') // 创建div
      //     div.innerHTML = response; // 将返回的form 放入div
      //     document.body.appendChild(div)
      //    document.forms[0].submit()
      //     //调用支付接口生成二维码
      //
      //    // _this.$router.push({path:'/payment',query: _this.order})
      // })
      axios({
        method: "post",
        url: "/api/pay/aliPay",
        data: postData,
      }).then((res) => {
        console.log(res.data);
        document.querySelector("body").innerHTML = res.data;
        const div = document.createElement("div"); // 创建div
        div.innerHTML = res.data; // 将返回的form 放入div
        document.body.appendChild(div);
        document.getElementsByName("punchout_form")[0].submit();
      });
    },
    remain(postData) {
      var _this = this;
      _this.$http
        .post("/order/balance-pay", postData)
        .then(function (response) {
          _this.order.code_url = response.data.code_url;
          //调用支付接口生成二维码

          _this.$router.push({ path: "/success", query: _this.order });
        });
    },
    creditpay(wechatData) {
      var _this = this;
      _this.$http
        .post("/order/credit-pay", wechatData)
        .then(function (response) {
          _this.order.code_url = response.data.code_url;
          //调用支付接口生成二维码

          _this.$router.push({ path: "/success", query: _this.order });
        });
    },
    //获取收获地址
    getAddress(){
      var _this = this;
      _this.$http
          .get("/member/address/list")
          .then(function (response) {
           _this.address = response.data;
           _this.postAddres = response.data[0].id;
            // _this.$message({
            //   showClose: true,
            //   message: response.message,
            //   type: "success",
            // });
            //调用支付接口生成二维码

            // _this.$router.push({ path: "/payment", query: _this.order });
          });
    },
    addressIdEvent(data){
      //window.console.log(data);
      this.postAddres = data;
    },
    //手机端微信支付封装
    wexinPay(data, cb, errorCb) {
      //获取后台传入的数据
      let appId = data.appId;
      let timestamp = data.timeStamp;
      let nonceStr = data.nonceStr;
      let signature = data.paySign;
      let packages = data.package;
      let paySign = data.paySign;
      let signType = data.signType;
      console.log('发起微信支付')
      //下面要发起微信支付了
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: appId, // 必填，公众号的唯一标识
        timestamp: timestamp, // 必填，生成签名的时间戳
        nonceStr: nonceStr, // 必填，生成签名的随机串
        signature: signature, // 必填，签名，见附录1
        jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
      wx.ready(function () {
        wx.chooseWXPay({
          timestamp: timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
          package: packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
          signType: signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: paySign, // 支付签名
          success: function (res) {
            // 支付成功后的回调函数
            cb(res);

          },
          fail: function (res) {
            //失败回调函数
            errorCb(res);
          }
        });
      });
      wx.error(function () {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        /*alert("config信息验证失败");*/
      });
    },
    _isMobile() {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag;
    },
    tosuccess(res){
      window.console.log(res);
      let _this = this;
      _this.$router.push({ path: "/success", query: _this.order });
    }
  },
  computed: {
    total: function () {
      let total = 0;
      total = this.num * this.product.price;
      return total;
    },
  },
};
</script>

<style lang="scss" scoped>
.middle-box {
  padding: 20px 0;
  .content-box {
    background: #fff;
    padding: 40px;
    text-align: left;
    h3 {
      font-size: 20px;
      color: #646464;
      padding-bottom: 10px;
    }
  }
  .table-box {
    text-align: center;

    .col-2 {
      width: 150px;
    }
    .col-3 {
      width: 200px;
    }
    .col-4 {
      width: 150px;
      color: #f40030;
    }
    .num {
      width: 50px;
      /deep/ input {
        text-align: center;
      }
    }
    .table-img {
      width: 120px;
      max-height: 100px;
      margin: 10px;
    }
    p {
      text-align: left;
      font-size: 18px;
      color: #333333;
    }
    span {
      text-align: left;
      font-size: 14px;
      color: #969696;
    }
  }
  .table-title {
    width: 100%;
    height: 50px;
    background-color: #f3f3f3;
    border: solid 1px #dcdcdc;
    color: #5b5b5b;
    font-size: 16px;
  }
  .table-list {
    width: 100%;
    border: solid 1px #dcdcdc;
    border-top: 0;
    .mobile-yxj {
      display: none;
    }
  }
  .info-box {
    width: 340px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin: 10px 0;
    span {
      width: 150px;
      padding: 10px;
      box-sizing: border-box;
    }
    /deep/ .el-input__inner {
      border: 0;
    }
  }
  .footer-box {
    border-top: solid 1px #dcdcdc;
    padding: 40px 0;
    margin-top: 100px;
    span {
      font-size: 14px;
    }
    b {
      font-size: 24px;
      color: #f40030;
    }
    .sub-btn {
      width: 160px;
      height: 50px;
      background-color: #f40030;
      margin-left: 20px;
    }
  }
}

/*手机端*/
@media (min-width: 320px) and (max-width: 800px) {
  .nav-1200 {
    padding: 0 20px;
    box-sizing: border-box;
  }
  .middle-box {
    padding: 0;

    .content-box {
      box-sizing: border-box;
      padding: 0 20px;
      .table-title {
        display: none;
      }
      .table-list {
        display: block;
        border: none;
        .mobile-yxj {
          display: inline-block;
        }
        .title-box {
          justify-content: end;
        }
        .mobile-money {
          line-height: 30px;
          text-align: left;
        }
        .mobile-s-num {
          justify-content: end;
        }
        .mobile-totle {
          line-height: 30px;
          text-align: left;
          display: none;
        }
      }
      .footer-box {
        margin: 0;
        padding-bottom: 0;
        position: absolute;
        bottom: 0;
        left:0;
        width: 100%;
        z-index: 99;
        background: #fff;
        padding: 12px 0;
      }
      .info-box{
        width: 290px;
        margin:10px 0 0 0 ;
      }
    }
  }
}
</style>
